package name.wilbur.course.db.bigone.ui;

import name.wilbur.course.db.bigone.control.LoginMgr;
import name.wilbur.course.db.bigone.dao.DAOFactory;
import name.wilbur.course.db.bigone.model.User;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class LoginWin extends BaseWindow {
	LoginMgr mgr;
	private Text name_text = null;
	private Label name_label = null;
	private Label pass_label = null;  //  @jve:decl-index=0:
	private Text pass_text = null;
	private Button submit = null;
	private Button register_b = null;
	
	public LoginWin() {
		super();
		mgr = new LoginMgr();
	}
	public LoginWin(Display disp) {
		super(disp);
		mgr = new LoginMgr();
	}
	/**
	 * This method initializes sShell
	 */
	public void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		
		sShell = new Shell();
		sShell.setText("用户登录");
		sShell.setLayout(gridLayout);
		sShell.setSize(new Point(200, 150));
		name_label = new Label(sShell, SWT.RIGHT);
		name_label.setText("用户名");
		name_text = new Text(sShell, SWT.BORDER | SWT.SINGLE);
		name_text.setLayoutData(data);
		pass_label = new Label(sShell, SWT.RIGHT);
		pass_label.setText("密码");
		pass_text = new Text(sShell, SWT.BORDER | SWT.SINGLE);
		pass_text.setLayoutData(data);
		pass_text.setEchoChar('*');
		submit = new Button(sShell, SWT.NONE);
		submit.setText("登录");
		register_b = new Button(sShell, SWT.NONE);
		register_b.setText("注册");
		register_b.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
			public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
				close();
				RegisterWin rw = new RegisterWin(getDisplay());
				rw.open();
			}
		});
		submit.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
			public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
				User me = mgr.login(name_text.getText(), pass_text.getText());
				if (me == null) {
					MessageBox warnBox = new MessageBox(sShell, SWT.OK);
					warnBox.setText("警告");
					warnBox.setMessage("用户名或密码不正确");
					warnBox.open();
					pass_text.setText("");
				} else {
					close();
					// check user level
					if (me.getAdmin() == true) {
						DAOFactory.authorize(DAOFactory.DBA_LEVEL.ADMIN);
						AdminWin win = new AdminWin(disp, mgr.getSession());
						win.open();
					} else {
						MainWin win = new MainWin(getDisplay(), mgr.getSession());
						win.open();
					}
				}
			}
		});
	}
}
